import React, {Component} from 'react';
import PropTypes from 'prop-types';
import axios from 'axios'

export default class Main extends Component {


    static propTypes = {
        searchName: PropTypes.string.isRequired,
    }

    state = {
        initView: true,
        loading: false,
        users: null,
        errorMessage: null
    }

    //当组件接收到 新的属性是调用
    componentWillReceiveProps(newProps, nextContext) {
        const {searchName} = newProps
        const oldSearchName = this.props.searchName
        console.log(searchName);
        console.log(oldSearchName);
        if (searchName === oldSearchName) {
            return
        }
        this.setState({loading: true, initView: false})
        const url = `https://api.github.com/search/users?q=${searchName}`

        axios.get(url)
            .then((res) => {
                console.log(res);
                const users = res.data.items.map((item) => ({
                    name: item.login,
                    url: item.html_url,
                    avatarUrl: item.avatar_url,
                }))
                this.setState({loading: false, users: users})

            }).catch((err) => {
                this.setState({loading: false, errorMessage: err.message})
            })

    }

    render() {
        const {searchName} = this.props
        const {initView, loading, users, errorMessage} = this.state;
        if (initView) {
            return <h2>请输入关键词进行搜索{searchName}</h2>
        } else if (loading) {
            return <h2>正在请求中....</h2>
        } else if (errorMessage) {
            return <h2>{errorMessage}</h2>
        } else {
            return (
                <div className="row">
                    {
                        users.map((user, index) => (
                            <div key={index} className="card">
                                <a href={user.url} target="_blank">
                                    <img src={user.avatarUrl}
                                         style={{width: 200}}/>
                                </a>
                                <p className="card-text">{user.name}</p>
                            </div>
                        ))
                    }
                </div>
            )

        }
    }
}
